<?php

namespace App\Http\Controllers\API\Activity;

use DB;
use Auth;
use Validator;
use App\Models\API\Activity;
use Illuminate\Http\Request;
use App\Services\AliyunOSS\OSS;
use App\Http\Controllers\API\APIController;

class ActivityController extends APIController
{
    public function fromMe()
    {
        $userId = Auth::user()->id;
        // 当前用户发布的活动
        $fromMe = Activity::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->join('users', 'activities.user_id', '=', 'users.id')
            ->select('activities.*', 'users.user_name', 'users.user_img')
            ->withCount('activityApply', 'activityJoin')
            ->paginate(10);
        return response()->json($this->setJson(true, $fromMe), 200);
    }

    public function join()
    {
        $userId = Auth::user()->id;
        // 当前用户的参加
        $join = \App\Models\API\ActivityJoin::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->with(['activity' => function($query) {
                $query->join('users', 'activities.user_id', '=', 'users.id')
                    ->select('activities.*', 'users.user_name', 'users.user_img')
                    ->withCount('activityApply', 'activityJoin');
            }])
            ->paginate(10);
        return response()->json($this->setJson(true, $join), 200);
    }

    public function fromUser(Request $request)
    {
        $userId = $request->get('user_id');
        // 目标用户发布的活动
        $fromMe = Activity::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->join('users', 'activities.user_id', '=', 'users.id')
            ->select('activities.*', 'users.user_name', 'users.user_img')
            ->withCount('activityApply', 'activityJoin')
            ->paginate(10);
        return response()->json($this->setJson(true, $fromMe), 200);
    }

    public function store(Request $request)
    {
        $v = Validator::make($request->all(), [
            'user_id'   => 'required',
            'title'    => 'required|max:60',
            'theme'    => 'required|max:4',
            'cover'    => 'required',
            'start_time' => 'required|max:24',
            'end_time'   => 'max:24',
            'details'   => 'max:255',
            'address'   => 'max:255',
            'number_of_people' => 'nullable|integer',
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {
            $inputData = $request->all();
            $inputData['cover'] = $this->upload($request->get('user_id'), $request->get('cover'));
            Activity::create($inputData);
            return response()->json($this->setJson(true, 'create_activity_succeed'), 200);
        }
    }

    public function show(Request $request, $id)
    {
        $userId = Auth::user()->id;
        $checkThis = false;
        
        $activity = Activity::where('activities.id', $id)
        ->join('users', 'activities.user_id', '=', 'users.id')
        ->select('activities.*', 'users.user_name', 'users.user_img')
        ->first();

        return response()->json($this->setJson(true, $activity), 200);
    }

    public function update(Request $request, $id)
    {
        $v = Validator::make($request->all(), [
            'user_id'   => 'required',
            'title'    => 'required|max:60',
            'theme'    => 'required|max:4',
            'start_time' => 'required|max:24',
            'end_time'   => 'max:24',
            'details'   => 'max:255',
            'address'   => 'max:255',
            'number_of_people' => 'nullable|integer',
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {
            $activity = Activity::find($id);

            $inputData = $request->all();
            $inputData['cover'] = $this->upload($request->get('user_id'), $request->get('cover'), $activity->cover);
            
            // $activity->user_id   = $inputData['user_id'];
            $activity->title = $inputData['title'];
            $activity->theme = $inputData['theme'];
            $activity->cover = $inputData['cover'];
            $activity->start_time = $inputData['start_time'];

            if (!empty($inputData['end_time'])) {
                $activity->end_time = $inputData['end_time'];
            }else{
                $activity->end_time = null;
            }

            if (!empty($inputData['details'])) {
                $activity->details = $inputData['details'];
            }else{
                $activity->details = null;
            }

            if (!empty($inputData['number_of_people'])) {
                $activity->number_of_people = $inputData['number_of_people'];
            }else{
                $activity->number_of_people = 0;
            }

            if (!empty($inputData['address'])) {
                $activity->address = $inputData['address'];
            }else{
                $activity->address = null;
            }

            $activity->save();
            return response()->json($this->setJson(true, 'update_activity_succeed'), 200);
        }
    }

    public function destroy(Request $request, $id)
    {
        $v = Validator::make($request->all(), [
            'user_id'   => 'required'
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {
            $userId = $request->get('user_id');

            $activity = Activity::where([
                ['id', '=', $id],
                ['user_id', '=', $userId]
            ])->first();

            OSS::deleteObject(substr($activity->cover, -19));
            
            $activity->delete();

            return response()->json($this->setJson(true, 'delete_activity_succeed'), 200);
        }
    }

    /**
     * 规范JSON
     *
     * @return Array
     */
    private function setJson($status, $msg)
    {
        $res = [
            'status' => $status,
            'msg'    => $msg
        ];
        return $res;
    }

    /**
     * 上传图片
     *
     * @return string
     */
    private function upload($userId, $base64, $oldUrl = false)
    {
        $base64Url = explode(',', $base64);

        if (count($base64Url) === 1) {
            return $base64;
        } else {
            $img = base64_decode($base64Url[1]);
            // 文件名 userId + 秒 + 随机数 + .jpg
            $time = time();
            $rand = mt_rand(0000, 9999);
            $fileName = $userId.$time.$rand.'.jpg';
            $res = OSS::upload($fileName, $img);
            $pathName = 'http://imlooke.oss-cn-qingdao.aliyuncs.com/'.$fileName;

            if ($oldUrl != false) {
                $res = OSS::deleteObject(substr($oldUrl, -19));
            }
            return $pathName;
        }
    }
}
